import Pagination from '@/components/Pagination'
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react'
import { Card, CardContent } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Search, ImageIcon, Video as FileVideo, FileAudio, X } from 'lucide-react'
import { useFileStore, type FileItem, type FilterState } from '@/stores/fileStore'
import { cn } from '@/lib/utils'
import FileUploadButton from '@/components/FileUploadButton'
import { type UploadResponse } from '@/services'
import { toast } from '@/hooks/use-toast'

interface FileSelectorProps {
  onConfirm: (files: FileItem) => void
  onCancel: () => void
  fType: string // 'image' | 'audio' | 'video' | 'document'
  multiple?: boolean
}

const ITEMS_PER_PAGE = 10

const FileSelector: React.FC<FileSelectorProps> = ({
  onConfirm,
  onCancel,
  multiple = false,
  fType, // 'image' | 'audio' | 'video' | 'document'
}) => {
  const uploadCallback = useRef<null | (() => Promise<UploadResponse>)>(null)
  const [searchTerm, setSearchTerm] = useState('')
  const {
    tagList,
    getTagList,
    files: sourceList,
    totalRecords,
    setFiles: setSourceList,
    fetchFiles,
  } = useFileStore()
  // 添加分页相关状态
  const [currentPage, setCurrentPage] = useState(1)
  const [filters, setFilters] = useState<FilterState>({
    type: '全部',
    timeRange: '全部',
    sortBy: '时间降序',
    tags: '',
    public: 'all',
  })
  // const [viewType, setViewType] = useState('preview')

  // console.log('获取文件数据', sourceList)

  const handleSearch = useCallback(
    (pageNum: number = 1, currentFilter: FilterState) => {
      fetchFiles({
        keywords: searchTerm,
        pageNum,
        pageSize: ITEMS_PER_PAGE,
        exts: fType,
        tags: currentFilter.tags === 'all' ? '' : currentFilter.tags,
        public:
          currentFilter.public === 'all'
            ? undefined
            : currentFilter.public === '1'
              ? 1
              : 0,
      })
    },
    [fetchFiles, searchTerm, fType],
  )

  const handlePageChange = useCallback(
    (pageNum: number = 1, currentFilter?: FilterState) => {
      setCurrentPage(pageNum)
      handleSearch(pageNum, currentFilter || filters)
    },
    [handleSearch, filters],
  )

  useEffect(() => {
    handleSearch(1, filters)
    getTagList()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  const totalPages = useMemo(() => {
    return Math.ceil(totalRecords / ITEMS_PER_PAGE)
  }, [totalRecords])

  const updateFilters = useCallback(
    (key: keyof FilterState, value: string) => {
      const newFilters = {
        ...filters,
        [key]: value,
      }
      setFilters(newFilters)
      handleSearch(1, newFilters)
    },
    [filters, handleSearch],
  )

  // 处理文件选择
  const handleFileSelect = (index: number) => {
    if (uploadCallback.current) {
      toast({
        variant: 'destructive',
        description: 'Please delete the local file first',
        duration: 2000,
      })
      return
    }

    // 单选
    if (!multiple) {
      sourceList.forEach((v, k) => (sourceList[k].selected = false))
    }
    sourceList[index].selected = !sourceList[index].selected
    setSourceList([...sourceList])
  }

  // 处理确认
  const handleConfirm = async () => {
    if (uploadCallback.current) {
      const fileInfo = await uploadCallback.current()
      onConfirm(fileInfo as any as FileItem)
      return
    }
    const selectedFiles = sourceList.filter((file) => file.selected)
    if (selectedFiles.length === 0) {
      toast({
        variant: 'destructive',
        description: 'Please select a file or upload a local file',
        duration: 2000,
      })
      return
    }

    onConfirm(selectedFiles[0])
  }

  const handleSetCallback = (fn: any) => {
    sourceList.forEach((v, k) => (sourceList[k].selected = false))
    setSourceList([...sourceList])
    uploadCallback.current = fn as () => Promise<UploadResponse>
  }

  // 获取文件图标
  const getFileIcon = (fileType: string) => {
    if (fileType.startsWith('image'))
      return <ImageIcon className="w-5 h-5 text-blue-500" />
    if (fileType.startsWith('audio'))
      return <FileAudio className="w-5 h-5 text-green-500" />
    return <FileVideo className="w-5 h-5 text-gray-500" />
  }
  // console.log('sourceList', sourceList)

  return (
    <Card className="w-full border-none bg-transparent shadow-none mx-auto">
      <CardContent className="p-0">
        <div className="space-y-4">
          {/* 搜索框 */}
          <div className="flex items-center gap-4">
            <div className="relative flex-1 flex items-center rounded-full max-w-md bg-white/10">
              <div
                onClick={() => {
                  handlePageChange()
                }}
                className="flex items-center h-full pl-3 cursor-pointer"
              >
                <Search className="h-5 w-5 text-white" />
              </div>
              <Input
                placeholder="Search file Name"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    handlePageChange()
                  }
                }}
                className="flex-1 bg-transparent border-none placeholder:text-white/40"
              />
            </div>
            <div className="flex gap-2 items-center">
              {/* <label className="text-sm whitespace-nowrap font-medium">标签</label> */}
              <Select
                value={filters.tags}
                onValueChange={(value) => updateFilters('tags', value)}
              >
                <SelectTrigger className="bg-white/5 rounded-full placeholder:text-white/40">
                  <SelectValue placeholder="All Tags" />
                </SelectTrigger>
                <SelectContent>
                  <SelectGroup>
                    <SelectItem key={'all'} value="all">
                      All Tags
                    </SelectItem>
                    {tagList.map((item) => {
                      return (
                        <SelectItem key={item.id} value={item.name}>
                          {item.name}
                        </SelectItem>
                      )
                    })}
                  </SelectGroup>
                </SelectContent>
              </Select>
            </div>
            <div className="flex gap-2 items-center">
              {/* <label className="text-sm whitespace-nowrap font-medium">资源</label> */}
              <Select
                value={filters.public}
                onValueChange={(value) => updateFilters('public', value)}
              >
                <SelectTrigger className="bg-white/5 rounded-full placeholder:text-white/40">
                  <SelectValue placeholder="My resource" />
                </SelectTrigger>
                <SelectContent>
                  <SelectGroup>
                    <SelectItem key={'all'} value="all">
                      All Resources
                    </SelectItem>
                    <SelectItem key="public" value="1">
                      Public Resources
                    </SelectItem>
                    <SelectItem key="my" value="0">
                      My Resources
                    </SelectItem>
                  </SelectGroup>
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 视图切换 */}
          {/* <RadioGroup
            value={viewType}
            onValueChange={setViewType}
            className="flex space-x-4"
          >
            <div className="flex items-center space-x-2">
              <RadioGroupItem value="preview" id="preview" />
              <Label htmlFor="preview">预览</Label>
            </div>
            <div className="flex items-center space-x-2">
              <RadioGroupItem value="file" id="file" />
              <Label htmlFor="file">文件</Label>
            </div>
          </RadioGroup> */}

          {/* 文件列表 */}
          <ScrollArea className="h-64 rounded-md">
            <div className="grid grid-cols-2 gap-5">
              {sourceList.map((file, index) => (
                <div
                  key={file.id}
                  className={`flex flex-col items-center cursor-pointer`}
                  onClick={() => handleFileSelect(index)}
                >
                  {/* <div className="flex-shrink-0">{getFileIcon(file.fileType)}</div> */}
                  <div
                    className={cn(
                      'h-52 w-full bg-white/10 hover:border-white border p-1 rounded-lg',
                      file.selected && 'border-white',
                      // file.fileType === 'video'
                      //   ? 'flex-1'
                      //   : 'w-12 flex justify-center',
                    )}
                  >
                    {file.fileType === 'video' ? (
                      <video
                        className="h-full w-full object-cover rounded-lg"
                        src={file.url}
                      ></video>
                    ) : (
                      <img
                        className="h-full w-full object-cover rounded-lg"
                        src={file.url}
                        alt={file.name}
                      />
                    )}
                  </div>
                  <div className="p-2.5 text-sm text-white">{file.name}</div>
                </div>
              ))}
            </div>
          </ScrollArea>
          {sourceList.length > 0 && (
            <Pagination
              className="justify-end mb-4"
              isMini={true}
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={handlePageChange}
            />
          )}

          {/* 按钮组 */}
          <div className="flex flex-col gap-8 w-full">
            <div className="flex gap-4 w-full">
              <FileUploadButton
                className="flex-1"
                onExecUpload={(fn) => {
                  handleSetCallback(fn)
                }}
                accept={fType === 'image' ? 'image/*' : 'video/*'}
                maxSize={200 * 1024 * 1024}
                trigger={({ fileInfo, clearInfo }) => (
                  <div className="w-full relative">
                    <Button
                      variant="outline"
                      className="w-full border-[#A091FD] bg-white/10"
                    >
                      <div className="absolute inset-0 px-4 flex items-center">
                        <div className="w-full truncate">
                          {fileInfo?.name || 'Select Local File'}
                        </div>
                      </div>
                    </Button>
                    {fileInfo && (
                      <div
                        className="absolute p-[2px] right-1 mr-[-10px] mt-[-5px] border rounded-full top-0 cursor-pointer"
                        onClick={(event) => {
                          uploadCallback.current = null
                          event.preventDefault()
                          event.stopPropagation()
                          clearInfo()
                        }}
                      >
                        <X size="16" />
                      </div>
                    )}
                  </div>
                )}
              ></FileUploadButton>
            </div>
            <div className="flex items-center w-full justify-center">
              {/* <div className="flex-2">
                <Button variant="destructive" className="w-full" onClick={onCancel}>
                  Cancel
                </Button>
              </div> */}
              <Button className="w-80" size="lg" onClick={handleConfirm}>
                Confirm
              </Button>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

export default FileSelector
